module.exports = class Mcaptcha {
    constructor(options) {
        this.options = options;
        this.fontSize = options.height * 2 / 4;
        this.init();
        this.refresh(this.options.code);
    }
    init() {
        this.ctx = wx.createCanvasContext(this.options.el);
        this.ctx.setTextBaseline("middle");
        this.ctx.setFillStyle(this.randomColor(180, 240)); // 绘制背景色
        this.ctx.fillRect(0, 0, this.options.width, this.options.height);
    }
    refresh(code) {
        this.init();
        let arr = (code + '').split('');
        if (arr.length === 0) {
            arr = ['e', 'r', 'r', 'o', 'r'];
        };
        let offsetLeft = 12 // this.options.width * 0.6 / (arr.length - 1);
        let marginLeft = 10 // this.options.width * 0.2;
        arr.forEach((item, index) => {
            this.ctx.setFillStyle(this.randomColor(0, 180)); // 随机生成字体颜色
            let size = this.randomNum(20, this.fontSize);
            this.ctx.setFontSize(size); // 随机生成字体大小

            // 修改坐标原点和旋转角度
            let dis = offsetLeft * index + marginLeft - size * 0.2;
            let deg = this.randomNum(-20, 30); // 旋转角度
            this.ctx.translate(dis, this.options.height * 0.2);
            this.ctx.rotate(deg * Math.PI / 180);
            this.ctx.fillText(item, 0, 0);
            // 恢复坐标原点和旋转角度
            this.ctx.rotate(-deg * Math.PI / 180);
            this.ctx.translate(-dis, -this.options.height * 0.2);
        })
        /**绘制干扰线**/
        for (var i = 0; i < 4; i++) {
            this.ctx.strokeStyle = this.randomColor(40, 180);
            this.ctx.beginPath();
            this.ctx.moveTo(this.randomNum(0, 90), this.randomNum(0, 28));
            this.ctx.lineTo(this.randomNum(0, 90), this.randomNum(0, 28));
            this.ctx.stroke();
        }
        /**绘制干扰点**/
        for (var i = 0; i < 20; i++) {
            this.ctx.fillStyle = this.randomColor(0, 255);
            this.ctx.beginPath();
            this.ctx.arc(this.randomNum(0, 90), this.randomNum(0, 28), 1, 0, 2 * Math.PI);
            this.ctx.fill();
        }
        this.ctx.draw();
    }
    randomNum(min, max) {
        return Math.floor(Math.random() * (max - min) + min);
    }
    /**
     * 生成一个随机色
     * @param {Number} min 
     * @param {Number} max 
     */
    randomColor(min, max) {
        let r = this.randomNum(min, max);
        let g = this.randomNum(min, max);
        let b = this.randomNum(min, max);
        return "rgb(" + r + "," + g + "," + b + ")";
    }
}
